import { fetchDataMap, deleteUploadFile, dataImport, dataProgress } from '../services/DataImport';
import { message } from 'antd';
import { parse } from 'qs';

export default {
    namespace: 'DataImport',
    state: {
        display: false,
        hasColHeader: true,
        fileName: "",
        sheetNames: [],
        params: {},
        dataMaps: [],
        isNewMap: true,
        columns: [],
        step: 1,
        ignoreErr: false,
        dataMapsChange: false,
        success: false,
        successCount: 0,
        errorMsg: "",
        errorDatas: [],
        importing: false,
        timer: 0,
        process: {
            msg: "",
            percent: 0
        }
    },
    effects: {
        *fetchDataMap({ payload: { controls, importInfo, execImport } }, { call, put }) {
            const res = yield call(fetchDataMap, importInfo);
            if (res) {
                const data = res
                let dataMaps = data.dataMaps;
                let isNewMap = false
                if (dataMaps === null) {
                    isNewMap = true
                    dataMaps = []
                    controls.forEach((c) => {
                        let convert = null
                        if (c.data) {
                            let ids = [];
                            let texts = [];
                            c.data.map((d) => {
                                ids.push(d.value)
                                texts.push(d.label)
                            })
                            convert = { DaoName: "#fixed", IdColName: ids.join(":"), TextColName: texts.join(":") }
                            convert.Multiple = false
                        } else if (c.fetch) {
                            convert = { DaoName: c.fetch.daoName, IdColName: c.fetch.valueTpl, TextColName: c.fetch.optionTpl }
                            convert.Multiple = c.multiple ? true : false
                        }
                        const dMap = {
                            DestColName: c.name,
                            IsRequest: c.required ? true : false,
                            Convert: convert
                        }
                        dataMaps.push(dMap)
                    })
                }
                let params = importInfo.Params
                params.select_sheetName = importInfo.SheetName
                const hasColHeader = importInfo.HasColHeader
                const dataMapsChange = !data.success || isNewMap
                yield put({
                    type: 'setDataMap',
                    payload: {
                        params,
                        hasColHeader,
                        dataMaps,
                        columns: data.columns,
                        step: 2,
                        isNewMap,
                        dataMapsChange
                    },
                });
                if (!data.success) {
                    message.warn("检测到数据导入文件与映射关系不符，请修改映射关系或重新选择导入文件！", 5)
                } else {
                    if (execImport) {
                        if (isNewMap) {
                            message.warn("请先设置数据映射关系，再执行导入！")
                        } else {
                            yield put({
                                type: 'dataImport',
                                payload: {
                                    importInfo, ignoreErr: false, errorDatas: [], dataMaps, isNewMap: false
                                },
                            });
                        }
                    }
                }
            }
        },
        *dataImport({ payload: { importInfo, ignoreErr, errorDatas, dataMaps, isNewMap } }, { call, put }) {
            const res = yield call(dataImport, importInfo, ignoreErr, errorDatas, dataMaps, isNewMap);
            if (res === "ok") {
                yield put({
                    type: 'setImporting',
                    payload: {
                        importing: true,
                        timer: 0
                    },
                });
            }
        },
        *dataProgress({ payload: { fileName } }, { call, put }) {
            const res = yield call(dataProgress, fileName);
            if (res) {
                const data = res
                let step = 3
                let process = {
                    msg: "正在" + data.msg + "...",
                    percent: Number(data.percent)
                }
                if (data.finish === "1") {
                    let success = data.success === "1" ? true : false
                    process = { msg: "", percent: 0 }
                    yield put({
                        type: 'setImportResult',
                        payload: {
                            step: step, success: success, successCount: Number(data.successCount), errorDatas: data.errorDatas, errorMsg: data.err, importing: false, process
                        },
                    });
                } else {
                    yield put({
                        type: 'setProcess',
                        payload: {
                            process
                        },
                    });
                }
            } else {
                let step = 3
                yield put({
                    type: 'setImportResult',
                    payload: {
                        step: step, success: false, successCount: 0, errorDatas: [], errorMsg: "系统服务器端异常！", importing: false, process: null
                    },
                });
            }
        },
        *deleteUploadFile({ payload: { fileName } }, { call, put }) {
            yield call(deleteUploadFile, fileName);
            yield put({
                type: 'setUplodFile',
                payload: {
                    fileName: "", sheetNames: []
                },
            });
        }
    },
    reducers: {
        setDataMap(state, { payload: { params, hasColHeader, dataMaps, columns, step, isNewMap, dataMapsChange } }) {
            return { ...state, params, hasColHeader, dataMaps, columns, step, isNewMap, dataMapsChange };
        },
        setParams(state, { payload: { params } }) {
            return { ...state, params };
        },
        setImportResult(state, { payload: { step, success, successCount, errorDatas, errorMsg, importing, process } }) {
            const timer = state.timer
            if (timer > 0) {
                window.clearInterval(timer)
            }
            const dataMapsChange = false
            return { ...state, step, success, successCount, errorDatas, dataMapsChange, errorMsg, importing, timer: 0, process, ignoreErr: false };
        },
        setProcess(state, { payload: { process } }) {
            return { ...state, process };
        },
        setHasColHeader(state, { payload: { hasColHeader } }) {
            return { ...state, hasColHeader };
        },
        setIgnoreErr(state, { payload: { ignoreErr } }) {
            return { ...state, ignoreErr };
        },
        setDataMapsChange(state, { payload: { dataMapsChange } }) {
            return { ...state, dataMapsChange };
        },
        setErrorDatas(state, { payload: { errorDatas } }) {
            return { ...state, errorDatas };
        },
        setStep(state, { payload: { step } }) {
            return { ...state, step };
        },
        setDisplay(state, { payload: { display } }) {
            const step = 1
            const fileName = ""
            const isNewMap = true
            const dataMap = []
            return { ...state, display, step, fileName, isNewMap, dataMap };
        },
        setImporting(state, { payload: { importing, timer } }) {
            return { ...state, importing, timer };
        },
        setUplodFile(state, { payload: { fileName, sheetNames, dataMap } }) {
            const step = 1
            let params = state.params
            let isNewMap = true
            if (dataMap&&dataMap.length > 0) {
                isNewMap = false
            }
            return { ...state, step, fileName, sheetNames, params, dataMaps: dataMap, isNewMap };
        },
    }

};
